namespace RBAC.Write.Api.Application.Handler.ERP.InboundManagement
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.Dto.Output;
    using RBAC.Domain.MaterialManage;
    using RBAC.Domain.StorageManage;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Write.Api.Application.Command.ERP.InboundManagement;

    public class AddPurchaseStorageHandler : IRequestHandler<AddPurchaseStorageCommand, APIResult<long>>
    {
        private readonly IBaseRepository<PurchaseStorage> headerRepo;
        private readonly IBaseRepository<PurchaseStorageDetail> detailRepo;
        private readonly IBaseRepository<Mater> materRepo;
        private readonly ILogger<AddPurchaseStorageHandler> logger;

        public AddPurchaseStorageHandler(
            IBaseRepository<PurchaseStorage> headerRepo,
            IBaseRepository<PurchaseStorageDetail> detailRepo,
            IBaseRepository<Mater> materRepo,
            ILogger<AddPurchaseStorageHandler> logger)
        {
            this.headerRepo = headerRepo;
            this.detailRepo = detailRepo;
            this.materRepo = materRepo;
            this.logger = logger;
        }

        public Task<APIResult<long>> Handle(AddPurchaseStorageCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<long>();
            try
            {
                if (request.Data == null || request.Data.Details == null || request.Data.Details.Count == 0)
                {
                    result.Code = APIEnums.Fail;
                    result.Msg = "明细不能为空";
                    result.Data = 0;
                    return Task.FromResult(result);
                }

                var dto = request.Data;

                // 校验：明细中存在非空跟单编号(SalesOrderCode)时，判断是否已有入库单明细使用了该编号
                var followCodes = dto.Details
                    .Where(d => !string.IsNullOrWhiteSpace(d.SalesOrderCode))
                    .Select(d => d.SalesOrderCode!.Trim())
                    .Distinct()
                    .ToList();
                if (followCodes.Count > 0)
                {
                    var placeholders = string.Join(",", followCodes.Select((_, i) => $"@C{i}"));
                    var paramCodes = followCodes
                        .Select((c, i) => new { Key = $"@C{i}", Value = (object)c })
                        .ToDictionary(x => x.Key, x => x.Value);
                    // MySQL 查询任意一条已存在的编号
                    var existCode = headerRepo.QueryFirstOrDefault<string>(
                        $"SELECT SalesOrderCode FROM PurchaseStorageDetail WHERE IsDeleted = 0 AND SalesOrderCode IN ({placeholders}) LIMIT 1",
                        paramCodes);
                    if (!string.IsNullOrWhiteSpace(existCode))
                    {
                        result.Code = APIEnums.Fail;
                        result.Msg = $"{existCode}单据已生成入库单";
                        result.Data = 0;
                        return Task.FromResult(result);
                    }
                }

                // 校验物料是否存在
                var materIds = dto.Details.Select(d => d.MaterId).Distinct().ToList();
                if (materIds.Count > 0)
                {
                    var inClause = string.Join(",", materIds.Select((_, index) => $"@Id{index}"));
                    var parameters = materIds.Select((id, index) => new { Key = $"@Id{index}", Value = id })
                        .ToDictionary(x => x.Key, x => (object)x.Value);
                    var maters = materRepo.GetAll($"Id IN ({inClause})", parameters);
                    var validMaterIds = new HashSet<long>(maters.Select(m => m.Id));
                    var missing = materIds.Where(id => !validMaterIds.Contains(id)).ToList();
                    if (missing.Any())
                    {
                        result.Code = APIEnums.Fail;
                        result.Msg = $"存在无效物料ID: {string.Join(",", missing)}";
                        result.Data = 0;
                        return Task.FromResult(result);
                    }
                }

                var now = DateTime.Now;
                // 服务器端自动生成单据编码：CGRK + 年月日时分秒 + 2位随机数，必要时再补1位随机数
                string orderCode;
                int tryTimes = 0;
                var rand = new Random();
                while (true)
                {
                    var suffix = rand.Next(0, 100).ToString("D2");
                    orderCode = $"CGRK{now:yyyyMMddHHmmss}{suffix}";
                    // 唯一性校验，若存在则重试（最多5次），仍冲突则追加1位随机数再试3次
                    var exists = headerRepo.QueryFirstOrDefault<int>(
                        "SELECT COUNT(1) FROM PurchaseStorage WHERE OrderCode = @OrderCode",
                        new { OrderCode = orderCode });
                    if (exists == 0)
                        break;

                    tryTimes++;
                    if (tryTimes >= 5)
                    {
                        var suffix3 = rand.Next(0, 1000).ToString("D3");
                        orderCode = $"CGRK{now:yyyyMMddHHmmss}{suffix3}";
                        var exists2 = headerRepo.QueryFirstOrDefault<int>(
                            "SELECT COUNT(1) FROM PurchaseStorage WHERE OrderCode = @OrderCode",
                            new { OrderCode = orderCode });
                        if (exists2 == 0)
                            break;
                        // 继续少量重试
                        if (tryTimes >= 8)
                            throw new InvalidOperationException("生成唯一单据编码失败，请稍后再试");
                    }
                }
                var headerSql = @"START TRANSACTION;
INSERT INTO PurchaseStorage (OrderCode, OrderType, BusinessType, Operator, Warehouse, OrderDate, BusinessStatus, ArrivalNo, OrderStatus, BusinessDept, Supplier, BusinessPerson, Period, Remark, CreateUser, CreateTime, IsDeleted)
VALUES (@OrderCode, @OrderType, @BusinessType, @Operator, @Warehouse, @OrderDate, @BusinessStatus, @ArrivalNo, @OrderStatus, @BusinessDept, @Supplier, @BusinessPerson, @Period, @Remark, @CreateUser, @CreateTime, false);
SET @hid = LAST_INSERT_ID();
";
                var detailSqlParts = new List<string>();
                for (int i = 0; i < dto.Details.Count; i++)
                {
                    detailSqlParts.Add($"INSERT INTO PurchaseStorageDetail (PurchaseStorageId, MaterId, SalesOrderCode, Num, Remark, CreateUser, CreateTime, IsDeleted) VALUES (@hid, @D{i}_MaterId, @D{i}_SalesOrderCode, @D{i}_Num, @D{i}_Remark, @CreateUser, @CreateTime, false);");
                }
                var tailSql = "COMMIT; SELECT @hid AS Id;";
                var fullSql = headerSql + string.Join("\n", detailSqlParts) + tailSql;

                var param = new Dictionary<string, object?>
                {
                    ["OrderCode"] = orderCode,
                    ["OrderType"] = dto.OrderType ?? "入库单",
                    ["BusinessType"] = dto.BusinessType ?? "采购入库",
                    ["Operator"] = dto.Operator,
                    ["Warehouse"] = dto.Warehouse,
                    ["OrderDate"] = dto.OrderDate ?? now,
                    ["BusinessStatus"] = dto.BusinessStatus ?? "正常",
                    ["ArrivalNo"] = dto.ArrivalNo,
                    ["OrderStatus"] = dto.OrderStatus ?? "开立",
                    ["BusinessDept"] = dto.BusinessDept,
                    ["Supplier"] = dto.Supplier,
                    ["BusinessPerson"] = dto.BusinessPerson,
                    ["Period"] = dto.Period,
                    ["Remark"] = dto.Remark,
                    ["CreateUser"] = dto.CreateUser,
                    ["CreateTime"] = now
                };

                for (int i = 0; i < dto.Details.Count; i++)
                {
                    var d = dto.Details[i];
                    param[$"D{i}_MaterId"] = d.MaterId;
                    param[$"D{i}_SalesOrderCode"] = d.SalesOrderCode;
                    param[$"D{i}_Num"] = d.Num;
                    param[$"D{i}_Remark"] = d.Remark;
                }

                long newId = 0;
                try
                {
                    newId = headerRepo.QueryFirstOrDefault<long>(fullSql, param);
                }
                catch
                {
                    headerRepo.Execute("ROLLBACK;");
                    throw;
                }

                result.Code = APIEnums.Success;
                result.Msg = "新增采购入库成功";
                result.Data = newId;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "新增采购入库失败: {Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "新增采购入库失败";
                result.Data = 0;
            }

            return Task.FromResult(result);
        }
    }
}
